package com.ruoyi.functiontest.controller;

import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.math.BigDecimal;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.functiontest.domain.TollAccessStatTest;
import com.ruoyi.functiontest.service.ITollAccessStatTestService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.web.multipart.MultipartFile;

/**
 * 联网收费切入数据实测统计测试Controller
 * 
 * @author ruoyi
 * @date 2025-09-25
 */
@RestController
@RequestMapping("/functiontest/TollAccessStatTest")
public class TollAccessStatTestController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(TollAccessStatTestController.class);
    
    @Autowired
    private ITollAccessStatTestService tollAccessStatTestService;

    /**
     * 查询联网收费切入数据实测统计测试列表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollAccessStatTest:list')")
    @GetMapping("/list")
    public AjaxResult list(TollAccessStatTest tollAccessStatTest)
    {
        List<TollAccessStatTest> list = tollAccessStatTestService.selectTollAccessStatTestList(tollAccessStatTest);
        
        // 判断是否有搜索条件，如果有则构建树形结构返回
        boolean hasSearchCondition = tollAccessStatTest.getRoadName() != null && !tollAccessStatTest.getRoadName().isEmpty() ||
                                   tollAccessStatTest.getNodeName() != null && !tollAccessStatTest.getNodeName().isEmpty();
        
        if (hasSearchCondition) {
            // 有搜索条件时，构建树形结构返回，包含匹配节点及其所有子节点
            List<TollAccessStatTest> treeList = buildTree(list);
            return success(treeList);
        } else {
            // 无搜索条件时，返回扁平列表
            return success(list);
        }
    }

    /**
     * 导出联网收费切入数据实测统计测试列表
     * 简化导出逻辑：直接导出数据库原始存储格式，无需树形结构处理
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollAccessStatTest:export')")
    @Log(title = "联网收费切入数据实测统计测试", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TollAccessStatTest tollAccessStatTest)
    {
        // 简化导出逻辑：直接导出数据库原始存储格式，无需树形结构处理
        List<TollAccessStatTest> list = tollAccessStatTestService.selectTollAccessStatTestList(tollAccessStatTest);
        
        ExcelUtil<TollAccessStatTest> util = new ExcelUtil<TollAccessStatTest>(TollAccessStatTest.class);
        util.exportExcel(response, list, "联网收费切入数据实测统计测试数据");
    }

    /**
     * 树形导出联网收费切入数据实测统计测试列表
     * 参考EtcGantryTreeTestController实现树节点的所有子树排序导出
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollAccessStatTest:export')")
    @Log(title = "联网收费切入数据实测统计测试", businessType = BusinessType.EXPORT)
    @PostMapping("/exportTree")
    public void exportTree(HttpServletResponse response, TollAccessStatTest tollAccessStatTest)
    {
        List<TollAccessStatTest> list = tollAccessStatTestService.selectTollAccessStatTestList(tollAccessStatTest);
        
        // 构建树形结构
        List<TollAccessStatTest> treeList = buildTree(list);
        
        // 将树形结构按层次顺序展平为列表
        List<TollAccessStatTest> exportList = new ArrayList<>();
        flattenTree(treeList, exportList);
        
        ExcelUtil<TollAccessStatTest> util = new ExcelUtil<TollAccessStatTest>(TollAccessStatTest.class);
        util.exportExcel(response, exportList, "联网收费切入数据实测统计测试数据（树形结构）");
    }

    /**
     * 获取联网收费切入数据实测统计测试详细信息
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollAccessStatTest:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tollAccessStatTestService.selectTollAccessStatTestById(id));
    }

    /**
     * 新增联网收费切入数据实测统计测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollAccessStatTest:add')")
    @Log(title = "联网收费切入数据实测统计测试", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TollAccessStatTest tollAccessStatTest)
    {
        int result = tollAccessStatTestService.insertTollAccessStatTest(tollAccessStatTest);
        if (result > 0) {
            // 插入成功后返回包含ID的完整对象
            return success(tollAccessStatTest);
        } else {
            return error("新增失败");
        }
    }

    /**
     * 导入联网收费切入数据实测统计测试数据
     * 简化导入逻辑：直接按照Excel原始格式导入，通过id和parentid来确定数据
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollAccessStatTest:import')")
    @Log(title = "联网收费切入数据实测统计测试", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<TollAccessStatTest> util = new ExcelUtil<TollAccessStatTest>(TollAccessStatTest.class);
        List<TollAccessStatTest> tollAccessStatTestList = util.importExcel(file.getInputStream());
        String message = tollAccessStatTestService.importTollAccessStatTest(tollAccessStatTestList, updateSupport);
        return success(message);
    }

    /**
     * 导入模板下载
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollAccessStatTest:import')")
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        List<TollAccessStatTest> templateList = new ArrayList<>();
        
        // 六安根节点
        TollAccessStatTest liuanRoot = new TollAccessStatTest();
        liuanRoot.setId(1L);
        liuanRoot.setParentId(0L);
        liuanRoot.setRoadName("六安");
        liuanRoot.setNodeName("");
        liuanRoot.setDirection("");
        liuanRoot.setDistance(null);
        liuanRoot.setAvgDistance(null);
        liuanRoot.setTableName("");
        liuanRoot.setRemark("");
        templateList.add(liuanRoot);
        
        // 六安-表1节点
        TollAccessStatTest liuanTable1 = new TollAccessStatTest();
        liuanTable1.setId(2L);
        liuanTable1.setParentId(1L);
        liuanTable1.setRoadName("");
        liuanTable1.setNodeName("表1");
        liuanTable1.setDirection("");
        liuanTable1.setDistance(null);
        liuanTable1.setAvgDistance(null);
        liuanTable1.setTableName("");
        liuanTable1.setImage("/profile/upload/2025/09/11/111_20250911191844A007.png");
        liuanTable1.setRemark("");
        templateList.add(liuanTable1);
        
        // P5-P6节点
        TollAccessStatTest p5p6 = new TollAccessStatTest();
        p5p6.setId(3L);
        p5p6.setParentId(2L);
        p5p6.setRoadName("");
        p5p6.setNodeName("P5—P6");
        p5p6.setDirection("");
        p5p6.setDistance(new BigDecimal("2354.240"));
        p5p6.setAvgDistance(null);
        p5p6.setTableName("");
        p5p6.setRemark("");
        templateList.add(p5p6);
        
        // P5->P6方向
        TollAccessStatTest p5ToP6 = new TollAccessStatTest();
        p5ToP6.setId(4L);
        p5ToP6.setParentId(3L);
        p5ToP6.setRoadName("");
        p5ToP6.setNodeName("P5—>P6");
        p5ToP6.setDirection("");
        p5ToP6.setDistance(new BigDecimal("2349.670"));
        p5ToP6.setAvgDistance(null);
        p5ToP6.setTableName("");
        p5ToP6.setRemark("属于都香高速");
        templateList.add(p5ToP6);
        
        // P6->P5方向
        TollAccessStatTest p6ToP5 = new TollAccessStatTest();
        p6ToP5.setId(5L);
        p6ToP5.setParentId(3L);
        p6ToP5.setRoadName("");
        p6ToP5.setNodeName("P6—>P5");
        p6ToP5.setDirection("");
        p6ToP5.setDistance(new BigDecimal("2358.810"));
        p6ToP5.setAvgDistance(null);
        p6ToP5.setTableName("");
        p6ToP5.setRemark("属于都香高速");
        templateList.add(p6ToP5);
        
        // P6-P7节点
        TollAccessStatTest p6p7 = new TollAccessStatTest();
        p6p7.setId(16L);
        p6p7.setParentId(2L);
        p6p7.setRoadName("");
        p6p7.setNodeName("P6—P7");
        p6p7.setDirection("");
        p6p7.setDistance(new BigDecimal("8673.740"));
        p6p7.setAvgDistance(null);
        p6p7.setTableName("");
        p6p7.setRemark("");
        templateList.add(p6p7);
        
        // P6->P7方向
        TollAccessStatTest p6ToP7 = new TollAccessStatTest();
        p6ToP7.setId(17L);
        p6ToP7.setParentId(16L);
        p6ToP7.setRoadName("");
        p6ToP7.setNodeName("P6—>P7");
        p6ToP7.setDirection("");
        p6ToP7.setDistance(new BigDecimal("8681.470"));
        p6ToP7.setAvgDistance(null);
        p6ToP7.setTableName("");
        p6ToP7.setRemark("");
        templateList.add(p6ToP7);
        
        // P7->P6方向
        TollAccessStatTest p7ToP6 = new TollAccessStatTest();
        p7ToP6.setId(18L);
        p7ToP6.setParentId(16L);
        p7ToP6.setRoadName("");
        p7ToP6.setNodeName("P7—>P6");
        p7ToP6.setDirection("");
        p7ToP6.setDistance(new BigDecimal("8666.000"));
        p7ToP6.setAvgDistance(null);
        p7ToP6.setTableName("");
        p7ToP6.setRemark("");
        templateList.add(p7ToP6);
        
        // P4-P5节点
        TollAccessStatTest p4p5 = new TollAccessStatTest();
        p4p5.setId(23L);
        p4p5.setParentId(2L);
        p4p5.setRoadName("");
        p4p5.setNodeName("P4—P5");
        p4p5.setDirection("");
        p4p5.setDistance(new BigDecimal("9019.350"));
        p4p5.setAvgDistance(null);
        p4p5.setTableName("");
        p4p5.setRemark("");
        templateList.add(p4p5);
        
        // P4->P5方向
        TollAccessStatTest p4ToP5 = new TollAccessStatTest();
        p4ToP5.setId(24L);
        p4ToP5.setParentId(23L);
        p4ToP5.setRoadName("");
        p4ToP5.setNodeName("P4—>P5");
        p4ToP5.setDirection("");
        p4ToP5.setDistance(new BigDecimal("9028.130"));
        p4ToP5.setAvgDistance(null);
        p4ToP5.setTableName("");
        p4ToP5.setRemark("属于都香高速");
        templateList.add(p4ToP5);
        
        // P5->P4方向
        TollAccessStatTest p5ToP4 = new TollAccessStatTest();
        p5ToP4.setId(25L);
        p5ToP4.setParentId(23L);
        p5ToP4.setRoadName("");
        p5ToP4.setNodeName("P5—>P4");
        p5ToP4.setDirection("");
        p5ToP4.setDistance(new BigDecimal("9010.580"));
        p5ToP4.setAvgDistance(null);
        p5ToP4.setTableName("");
        p5ToP4.setRemark("属于都香高速");
        templateList.add(p5ToP4);
        
        // A/B/C/D节点
        TollAccessStatTest abcd = new TollAccessStatTest();
        abcd.setId(27L);
        abcd.setParentId(2L);
        abcd.setRoadName("");
        abcd.setNodeName("A/B/C/D");
        abcd.setDirection("");
        abcd.setDistance(new BigDecimal("939.990"));
        abcd.setAvgDistance(null);
        abcd.setTableName("");
        abcd.setRemark("");
        templateList.add(abcd);
        
        // A节点
        TollAccessStatTest aNode = new TollAccessStatTest();
        aNode.setId(28L);
        aNode.setParentId(27L);
        aNode.setRoadName("");
        aNode.setNodeName("A");
        aNode.setDirection("");
        aNode.setDistance(new BigDecimal("929.060"));
        aNode.setAvgDistance(null);
        aNode.setTableName("");
        aNode.setRemark("属于都香高速");
        templateList.add(aNode);
        
        // B节点
        TollAccessStatTest bNode = new TollAccessStatTest();
        bNode.setId(29L);
        bNode.setParentId(27L);
        bNode.setRoadName("");
        bNode.setNodeName("B");
        bNode.setDirection("");
        bNode.setDistance(new BigDecimal("761.010"));
        bNode.setAvgDistance(null);
        bNode.setTableName("");
        bNode.setRemark("属于都香高速");
        templateList.add(bNode);
        
        // C节点
        TollAccessStatTest cNode = new TollAccessStatTest();
        cNode.setId(30L);
        cNode.setParentId(27L);
        cNode.setRoadName("");
        cNode.setNodeName("C");
        cNode.setDirection("");
        cNode.setDistance(new BigDecimal("944.710"));
        cNode.setAvgDistance(null);
        cNode.setTableName("");
        cNode.setRemark("属于都香高速");
        templateList.add(cNode);
        
        // D节点
        TollAccessStatTest dNode = new TollAccessStatTest();
        dNode.setId(31L);
        dNode.setParentId(27L);
        dNode.setRoadName("");
        dNode.setNodeName("D");
        dNode.setDirection("");
        dNode.setDistance(new BigDecimal("1125.170"));
        dNode.setAvgDistance(null);
        dNode.setTableName("");
        dNode.setRemark("属于都香高速");
        templateList.add(dNode);
        
        // K/M节点
        TollAccessStatTest km = new TollAccessStatTest();
        km.setId(34L);
        km.setParentId(2L);
        km.setRoadName("");
        km.setNodeName("K/M");
        km.setDirection("");
        km.setDistance(new BigDecimal("914.320"));
        km.setAvgDistance(null);
        km.setTableName("");
        km.setRemark("");
        templateList.add(km);
        
        // K节点
        TollAccessStatTest kNode = new TollAccessStatTest();
        kNode.setId(35L);
        kNode.setParentId(34L);
        kNode.setRoadName("");
        kNode.setNodeName("K");
        kNode.setDirection("");
        kNode.setDistance(new BigDecimal("805.900"));
        kNode.setAvgDistance(null);
        kNode.setTableName("");
        kNode.setRemark("");
        templateList.add(kNode);
        
        // 纳晴根节点
        TollAccessStatTest naqingRoot = new TollAccessStatTest();
        naqingRoot.setId(36L);
        naqingRoot.setParentId(0L);
        naqingRoot.setRoadName("纳晴");
        naqingRoot.setNodeName("");
        naqingRoot.setDirection("");
        naqingRoot.setDistance(null);
        naqingRoot.setAvgDistance(null);
        naqingRoot.setTableName("");
        naqingRoot.setRemark("");
        templateList.add(naqingRoot);
        
        // M节点
        TollAccessStatTest mNode = new TollAccessStatTest();
        mNode.setId(37L);
        mNode.setParentId(34L);
        mNode.setRoadName("");
        mNode.setNodeName("M");
        mNode.setDirection("");
        mNode.setDistance(new BigDecimal("1022.740"));
        mNode.setAvgDistance(null);
        mNode.setTableName("");
        mNode.setRemark("");
        templateList.add(mNode);
        
        // N/O节点
        TollAccessStatTest no = new TollAccessStatTest();
        no.setId(38L);
        no.setParentId(2L);
        no.setRoadName("");
        no.setNodeName("N/O");
        no.setDirection("");
        no.setDistance(new BigDecimal("1004.830"));
        no.setAvgDistance(null);
        no.setTableName("");
        no.setRemark("");
        templateList.add(no);
        
        // N节点
        TollAccessStatTest nNode = new TollAccessStatTest();
        nNode.setId(40L);
        nNode.setParentId(38L);
        nNode.setRoadName("");
        nNode.setNodeName("N");
        nNode.setDirection("");
        nNode.setDistance(new BigDecimal("1228.000"));
        nNode.setAvgDistance(null);
        nNode.setTableName("");
        nNode.setRemark("");
        templateList.add(nNode);
        
        // O节点
        TollAccessStatTest oNode = new TollAccessStatTest();
        oNode.setId(41L);
        oNode.setParentId(38L);
        oNode.setRoadName("");
        oNode.setNodeName("O");
        oNode.setDirection("");
        oNode.setDistance(new BigDecimal("781.660"));
        oNode.setAvgDistance(null);
        oNode.setTableName("");
        oNode.setRemark("");
        templateList.add(oNode);
        
        // 纳晴-表1节点
        TollAccessStatTest naqingTable1 = new TollAccessStatTest();
        naqingTable1.setId(42L);
        naqingTable1.setParentId(36L);
        naqingTable1.setRoadName("");
        naqingTable1.setNodeName("表1");
        naqingTable1.setDirection("");
        naqingTable1.setDistance(null);
        naqingTable1.setAvgDistance(null);
        naqingTable1.setTableName("");
        naqingTable1.setImage("/profile/upload/2025/09/11/111_20250911192027A014.png");
        naqingTable1.setRemark("");
        templateList.add(naqingTable1);
        
        // E/F/G/H/I/J节点
        TollAccessStatTest efghij = new TollAccessStatTest();
        efghij.setId(43L);
        efghij.setParentId(2L);
        efghij.setRoadName("");
        efghij.setNodeName("E/F/G/H/I/J");
        efghij.setDirection("");
        efghij.setDistance(new BigDecimal("1420.030"));
        efghij.setAvgDistance(null);
        efghij.setTableName("");
        efghij.setRemark("");
        templateList.add(efghij);
        
        // 纳晴-P5-P6节点
        TollAccessStatTest naqingP5p6 = new TollAccessStatTest();
        naqingP5p6.setId(44L);
        naqingP5p6.setParentId(42L);
        naqingP5p6.setRoadName("");
        naqingP5p6.setNodeName("P5-P6");
        naqingP5p6.setDirection("");
        naqingP5p6.setDistance(new BigDecimal("942.250"));
        naqingP5p6.setAvgDistance(null);
        naqingP5p6.setTableName("");
        naqingP5p6.setRemark("");
        templateList.add(naqingP5p6);
        
        // E节点
        TollAccessStatTest eNode = new TollAccessStatTest();
        eNode.setId(45L);
        eNode.setParentId(43L);
        eNode.setRoadName("");
        eNode.setNodeName("E");
        eNode.setDirection("");
        eNode.setDistance(new BigDecimal("1823.730"));
        eNode.setAvgDistance(null);
        eNode.setTableName("");
        eNode.setRemark("");
        templateList.add(eNode);
        
        // F节点
        TollAccessStatTest fNode = new TollAccessStatTest();
        fNode.setId(46L);
        fNode.setParentId(43L);
        fNode.setRoadName("");
        fNode.setNodeName("F");
        fNode.setDirection("");
        fNode.setDistance(new BigDecimal("943.000"));
        fNode.setAvgDistance(null);
        fNode.setTableName("");
        fNode.setRemark("");
        templateList.add(fNode);
        
        ExcelUtil<TollAccessStatTest> util = new ExcelUtil<TollAccessStatTest>(TollAccessStatTest.class);
        util.exportExcel(response, templateList, "联网收费切入数据实测统计测试导入模板");
    }

    /**
     * 实测单位批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollAccessStatTest:fieldAudit')")
    @Log(title = "联网收费切入数据实测统计测试", businessType = BusinessType.UPDATE)
    @PostMapping("/fieldAudit/batch")
    public AjaxResult fieldAuditBatch()
    {
        try {
            // 批量更新所有记录的review1字段为0
            int updatedCount = tollAccessStatTestService.updateReview1ToZero();
            System.out.println("实测单位批量审核完成，更新记录数：" + updatedCount);
            return success("实测单位批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("实测单位批量审核失败：" + e.getMessage());
            return error("实测单位批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 业主批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollAccessStatTest:ownerAudit')")
    @Log(title = "联网收费切入数据实测统计测试", businessType = BusinessType.UPDATE)
    @PostMapping("/ownerAudit/batch")
    public AjaxResult ownerAuditBatch(@RequestBody Map<String, Object> params)
    {
        try {
            Long deptId = params.get("deptId") != null ? Long.valueOf(params.get("deptId").toString()) : null;
            Long roleId = params.get("roleId") != null ? Long.valueOf(params.get("roleId").toString()) : null;
            
            System.out.println("业主批量审核 - 审核所有数据，deptId: " + deptId + ", roleId: " + roleId);
            
            // 1. 校验所有数据的review1字段是否都为0
            boolean allReview1Zero = tollAccessStatTestService.checkAllReview1IsZero();
            if (!allReview1Zero) {
                return error("业主批量审核失败：存在未通过实测单位审核的数据，请先完成实测单位审核");
            }
            
            // 2. 构建查询条件
            TollAccessStatTest queryCondition = new TollAccessStatTest();
            queryCondition.setDeptId(deptId);
            queryCondition.setRoleId(roleId);
            
            // 3. 从params中提取查询条件
            if (params.get("roadName") != null) {
                queryCondition.setRoadName(params.get("roadName").toString());
            }
            if (params.get("nodeName") != null) {
                queryCondition.setNodeName(params.get("nodeName").toString());
            }
            
            // 4. 根据条件批量更新业主审核状态
            int updatedCount = tollAccessStatTestService.updateReview2ToZeroByCondition(queryCondition);
            
            System.out.println("业主批量审核完成，更新记录数：" + updatedCount);
            return success("业主批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("业主批量审核失败：" + e.getMessage());
            return error("业主批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 中心批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollAccessStatTest:centerAudit')")
    @Log(title = "联网收费切入数据实测统计测试", businessType = BusinessType.UPDATE)
    @PostMapping("/centerAudit/batch")
    public AjaxResult centerAuditBatch()
    {
        try {
            System.out.println("中心批量审核 - 审核所有数据");
            
            // 1. 校验所有数据的review1和review2字段是否都不为空且都为0
            boolean allReview1AndReview2Zero = tollAccessStatTestService.checkAllReview1AndReview2AreZero();
            if (!allReview1AndReview2Zero) {
                return error("中心批量审核失败：存在未通过实测单位审核或业主审核的数据，请先完成前序审核");
            }
            
            // 2. 批量更新中心审核状态
            int updatedCount = tollAccessStatTestService.updateReview3ToZero();
            
            System.out.println("中心批量审核完成，更新记录数：" + updatedCount);
            return success("中心批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("中心批量审核失败：" + e.getMessage());
            return error("中心批量审核失败：" + e.getMessage());
        }
    }

    /**
     * 修改联网收费切入数据实测统计测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollAccessStatTest:edit')")
    @Log(title = "联网收费切入数据实测统计测试", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TollAccessStatTest tollAccessStatTest)
    {
        return toAjax(tollAccessStatTestService.updateTollAccessStatTest(tollAccessStatTest));
    }

    /**
     * 删除联网收费切入数据实测统计测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollAccessStatTest:remove')")
    @Log(title = "联网收费切入数据实测统计测试", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        for (Long id : ids) {
            if (tollAccessStatTestService.hasChildById(id)) {
                return AjaxResult.error("节点存在子节点，请先删除子节点后再删除父节点");
            }
        }
        return toAjax(tollAccessStatTestService.deleteTollAccessStatTestByIds(ids));
    }

    /**
     * 构建树形结构
     */
    private List<TollAccessStatTest> buildTree(List<TollAccessStatTest> list) {
        // 构建父子关系映射
        Map<Long, TollAccessStatTest> nodeMap = new HashMap<>();
        List<TollAccessStatTest> rootNodes = new ArrayList<>();
        
        // 先将所有节点放入map中
        for (TollAccessStatTest node : list) {
            nodeMap.put(node.getId(), node);
        }
        
        // 构建父子关系
        for (TollAccessStatTest node : list) {
            Long parentId = node.getParentId();
            if (parentId != null && parentId != 0) {
                TollAccessStatTest parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<TollAccessStatTest>());
                    }
                    @SuppressWarnings("unchecked")
                    List<TollAccessStatTest> children = (List<TollAccessStatTest>) parent.getChildren();
                    children.add(node);
                }
            } else {
                rootNodes.add(node);
            }
        }
        
        return rootNodes;
    }
    
    /**
     * 将树形结构按层次顺序展平为列表
     */
    private void flattenTree(List<TollAccessStatTest> treeList, List<TollAccessStatTest> result) {
        for (TollAccessStatTest node : treeList) {
            // 添加当前节点到结果列表
            result.add(node);
            
            // 递归处理子节点
            if (node.getChildren() != null) {
                @SuppressWarnings("unchecked")
                List<TollAccessStatTest> children = (List<TollAccessStatTest>) node.getChildren();
                flattenTree(children, result);
            }
        }
    }
}
